package sg.edu.ntu.metaweb.storage;

import rice.Continuation;
import rice.p2p.commonapi.Message;
import rice.p2p.past.PastContent;
import sg.edu.ntu.metaweb.pastry.MetawebGCPastContent;
import sg.edu.ntu.metaweb.pastry.messages.RequestRateWebpageMessage;
import sg.edu.ntu.metaweb.pastry.messages.RequestWebpageDataMessage;
import sg.edu.ntu.metaweb.storage.data.Webpage;

public class RequestWebpageDataContinuation implements Continuation<PastContent, Exception> {

	StorageManager storageManager;
	Webpage page = null;
	Message msg = null;
	
	public RequestWebpageDataContinuation(StorageManager storageManager, Message msg) {
		this.storageManager = storageManager;
		this.msg = msg;
	}
	
	public void receiveResult(PastContent result) {
				
		if (result instanceof MetawebGCPastContent) {
			this.page = ((MetawebGCPastContent)result).getWebpage();
			
			if (msg instanceof RequestWebpageDataMessage) {
				this.storageManager.responseWebpageData((MetawebGCPastContent)result, (RequestWebpageDataMessage)msg);
			}
			else if (msg instanceof RequestRateWebpageMessage) {
				this.storageManager.responseRateWebpage((MetawebGCPastContent)result, (RequestRateWebpageMessage)msg);
			}
			else {
				System.out.println("[RequestWebpageDataContinuation] Unsupported message type");
			}
			
			
		} else {
			System.out.println("Wrong ContentType (or null)");
			
			if (msg instanceof RequestWebpageDataMessage) {
				this.storageManager.responseWebpageData((MetawebGCPastContent)result, (RequestWebpageDataMessage)msg);
			}
			else if (msg instanceof RequestRateWebpageMessage) {
				this.storageManager.responseRateWebpage((MetawebGCPastContent)result, (RequestRateWebpageMessage)msg);
			}
			else {
				System.out.println("[RequestWebpageDataContinuation] Unsupported message type");
			}
		}

	}

	public void receiveException(Exception result) {
		result.printStackTrace();
	}
	
}
